import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity, Image } from "react-native";
import { scaleSize } from '../../../utils/screen';
import { i18n } from '../../../i18n';
import FontText from '../FontText';
import Switch from '../Switch';
import InputItem from '../InputItem';
import _ from 'lodash';
import { CachedImage } from "react-native-img-cache";
import moment from 'moment';
import ImagePicker from 'react-native-image-crop-picker';
import ModalSelector from 'react-native-modal-selector';
import DateTimePicker from 'react-native-modal-datetime-picker';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

class RewardEditForm extends Component {
  constructor(props) {
    super(props);

    const { reward, products = [] } = props;

    this.state = {
      reward,
      image: {},
      isDateTimePickerVisible: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.reward !== nextProps.reward) {
      this.setState({
        reward: nextProps.reward,
        image: {},
        isDateTimePickerVisible: false,
      });
    }
  }

  onCancel() {
    const { onCancel } = this.props;
    onCancel && onCancel();
  }

  onSave() {
    const { reward, image } = this.state;
    const { onSave } = this.props;
    onSave && onSave({reward, image});
  }

  changeStatus(status) {
    this.setState({
      reward: {
        ...this.state.reward,
        status,
      },
    });
  }

  changeTitle(title) {
    this.setState({
      reward: {
        ...this.state.reward,
        title,
      },
    });
  }

  changeDescription(description) {
    this.setState({
      reward: {
        ...this.state.reward,
        description,
      },
    });
  }

  changePoint(value) {
    this.setState({
      reward: {
        ...this.state.reward,
        take_points: value,
      },
    });
  }

  changeSortOrder(value) {
    this.setState({
      reward: {
        ...this.state.reward,
        sort_order: value,
      },
    });
  }

  async chooseRewardImage() {
    try {
      const image = await ImagePicker.openPicker({
        compressImageMaxWidth: 350,
        compressImageMaxHeight: 350,
        cropping: true,
        mediaType: "photo",
        includeBase64: true,
        compressImageQuality:0.8
      });
      this.setState({ image });
    } catch (_) {
      // do nothing on cancelation
    }
  }

  renderRewardImage() {
    const { reward, image } = this.state;
    const hasRewardImage = !_.isEmpty(reward.image);
    const last_updated_ms = moment(reward.last_updated).unix();
    const hasChoosedImage = !_.isEmpty(image);

    if (hasChoosedImage) {
      return (
        <Image
          style={[styles.formImage, {resizeMode: 'contain'}]}
          source={{uri: image.path, width: image.width, height: image.height}}
        />
      );
    } else if (hasRewardImage) {
      const isLocalImage = !reward.image.startsWith('http');
      return (
        isLocalImage ?
        <Image
          style={styles.formImage}
          source={{uri: reward.image}}
        /> :
        <CachedImage
          style={styles.formImage}
          source={{uri: `${reward.image}?v=${last_updated_ms}`}}
        />
      );

      <Image />
    } else {
      return (
        <FontText
          font={'book'}
          style={styles.noImageText}
        >
          No Image
        </FontText>
      );
    }
  }

  displayedProductText() {
    const { reward: { product_id } } = this.state;
    const { products } = this.props;

    let productText = 'Please select';
    if (_.isNumber(product_id)) {
      const foundProduct = products.find(item => item.product_id === product_id);
      if (foundProduct) {
        productText = foundProduct.name;
      }
    }

    return productText;
  }

  showProductPicker() {
    this.selector.open();
  }

  changeProduct(selectedProduct) {
    const { product_id } = selectedProduct;
    this.setState({
      reward: {
        ...this.state.reward,
        product_id,
      },
    });
  }

  displayedExpiredDate() {
    const { reward } = this.state;
    const { date_expired } = reward;

    if (!_.isEmpty(date_expired)) {
      const m = moment(date_expired);
      if (m.isValid()) {
        return m.format('YYYY-MM-DD');
      }
    }

    return 'Please select';
  }

  getExpiredDate() {
    const { reward } = this.state;
    const { date_expired } = reward;

    if (!_.isEmpty(date_expired)) {
      const m = moment(date_expired);
      if (m.isValid()) {
        return new Date(date_expired);
      }
    }

    return new Date();
  }

  updateExpiredDate(date) {
    const date_expired = moment(date).format('YYYY-MM-DD');

    this.setState({
      reward: {
        ...this.state.reward,
        date_expired,
      },
    });

    this.hideDatePicker();
  }

  showDatePicker() {
    this.setState({ isDateTimePickerVisible: true });
  }

  hideDatePicker() {
    this.setState({ isDateTimePickerVisible: false });
  }

  render() {
    const { reward } = this.state;
    const { products } = this.props;
    const isEditing = _.has(reward, 'server_reward_id');

    return (
      <View style={styles.container}>
        <View style={styles.formHeader}>
          <TouchableOpacity
            onPress={() => this.onCancel()}
          >
            <FontText
              style={styles.formHeaderText}
              font={'book'}
            >
              {i18n.t("btns.cancel")}
            </FontText>
          </TouchableOpacity>
          <FontText
            style={[styles.formHeaderText, {color: "#fff"}]}
            font={'book'}
          >
            {
              isEditing ?
              i18n.t("office.reward.form.editrewardheadertitle") :
              i18n.t("office.reward.form.newrewardheadertitle")
            }
          </FontText>
          <TouchableOpacity
            onPress={() => this.onSave()}
          >
            <FontText
              style={styles.formHeaderText}
              font={'book'}
            >
              {i18n.t("btns.save")}
            </FontText>
          </TouchableOpacity>
        </View>
        <KeyboardAwareScrollView style={styles.formBody}>
          <View style={[styles.formGroup, {marginTop: scaleSize(0)}]}>
            <FontText
              font={'light'}
              style={styles.formLabelText}
            >
              Reward Image
            </FontText>
            <View style={styles.formImageContainer}>
              <TouchableOpacity
                style={styles.formImageBox}
                onPress={() => this.chooseRewardImage()}
              >
                { this.renderRewardImage() }
              </TouchableOpacity>
            </View>
          </View>
          <View style={[styles.formGroup, {marginTop: scaleSize(0)}]}>
            <FontText
              font={'light'}
              style={styles.formLabelText}
            >
              Status
            </FontText>
            <View style={styles.formControl}>
              <FontText
                style={styles.formControlText}
                font={'book'}
              >
                Enabled
              </FontText>
              <Switch
                checked={reward.status === 1 ? true : false}
                onPress={(checked) => this.changeStatus(checked ? 1 : 0)}
                height={scaleSize(30)}
              >
              </Switch>
            </View>
          </View>
          <View style={styles.formGroup}>
            <FontText
              font={'light'}
              style={styles.formLabelText}
            >
              Title
            </FontText>
            <View style={styles.formControl}>
              <InputItem
                style={styles.formControlText}
                valuChange={val=>this.changeTitle(val)}
                value={reward.title}
              />
            </View>
          </View>
          <View style={styles.formGroup}>
            <FontText
              font={'light'}
              style={styles.formLabelText}
            >
              Points to get reward
            </FontText>
            <View style={styles.formControl}>
              <InputItem
                style={styles.formControlText}
                valuChange={val => this.changePoint(val)}
                value={`${reward.take_points}`}
                keyboardType='numeric'
              />
            </View>
          </View>
          <View style={styles.formGroup}>
            <FontText
              font={'light'}
              style={styles.formLabelText}
            >
              Connected Product
            </FontText>
            <View style={styles.formControl}>
              <FontText
                style={styles.formControlText}
                font={'book'}
              >
                Product
              </FontText>
              <ModalSelector
                  data={products}
                  ref={selector => { this.selector = selector; }}
                  onChange={(option) => this.changeProduct(option)}
                  keyExtractor= {item => item.product_id}
                  labelExtractor= {item => item.name}
                  customSelector={
                    <TouchableOpacity
                      onPress={() => this.showProductPicker()}
                    >
                      <FontText
                        style={styles.formPickerText}
                        font={'book'}
                      >
                        {this.displayedProductText()} >
                      </FontText>
                    </TouchableOpacity>
                  }
              />
            </View>
          </View>
          <View style={styles.formGroup}>
            <FontText
              font={'light'}
              style={styles.formLabelText}
            >
              Expired data if specified
            </FontText>
            <View style={styles.formControl}>
              <FontText
                style={styles.formControlText}
                font={'book'}
              >
                Date Expired
              </FontText>
              <TouchableOpacity
                onPress={() => this.showDatePicker()}
              >
                <FontText
                  style={styles.formPickerText}
                  font={'book'}
                >
                  {this.displayedExpiredDate()} >
                </FontText>
              </TouchableOpacity>
              <DateTimePicker
                date={this.getExpiredDate()}
                isVisible={this.state.isDateTimePickerVisible}
                onConfirm={(date) => this.updateExpiredDate(date)}
                onCancel={() => this.hideDatePicker()}
              />
            </View>
          </View>
          <View style={styles.formGroup}>
            <FontText
              font={'light'}
              style={styles.formLabelText}
            >
              Sort order for displaying sequence
            </FontText>
            <View style={styles.formControl}>
              <InputItem
                style={styles.formControlText}
                valuChange={val => this.changeSortOrder(val)}
                value={`${reward.sort_order}`}
                keyboardType='numeric'
              />
            </View>
          </View>
          <View style={styles.formGroup}>
            <FontText
              font={'light'}
              style={styles.formLabelText}
            >
              Description
            </FontText>
            <View behavior="padding" keyboardVerticalOffset={50} style={styles.formControl}>
              <InputItem
                style={styles.formControlText}
                valuChange={val=>this.changeDescription(val)}
                value={reward.description}
              />
            </View>
          </View>
        </KeyboardAwareScrollView>
      </View>
    );
  }
}

/* StyleSheet =============================================================== */

const styles = StyleSheet.create({
  container: {
  },
  formHeader: {
    height: scaleSize(50),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: scaleSize(30),
  },
  formHeaderText: {
    color: "#fd265d",
    fontSize: scaleSize(30),
  },
  formBody: {
  },
  formImageContainer: {
    alignItems: 'center',
  },
  formImageBox: {
    width:scaleSize(352),
    height:scaleSize(352),
    borderColor: "#9b9b9b",
    borderWidth: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  formImage: {
    width:scaleSize(350),
    height:scaleSize(350),
  },
  noImageText: {
    color: "#fff",
  },
  formGroup: {
    marginTop: scaleSize(30),
  },
  formLabelText: {
    paddingLeft: scaleSize(30),
    color: "#9b9b9b",
    fontSize: scaleSize(20),
    lineHeight: scaleSize(50),
  },
  formControl: {
    backgroundColor: "#394158",
    paddingHorizontal: scaleSize(30),
    height: scaleSize(60),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  formControlText: {
    color:"#fff",
    fontSize: scaleSize(28),
  },
  formPickerText: {
    color: "#9b9b9b",
    fontSize: scaleSize(28),
  },
  formControlList: {
    flex: 1,
  },
});

export default RewardEditForm;
